const fs = require('fs');
const path = require('path');
let config = fs.readFileSync(path.join(__dirname,'./wdConfig.json'), 'utf8');
let res=null;
config = JSON.parse(config);
const TARGET_PATH=path.join(config.android.platform.buildPath,"jsb-default/frameworks/runtime-src/proj.android-studio");
let analytics=config.android.analytics;
analyticsFunc();

function analyticsFunc() {
        if(analytics[0].enable==true){
            res = fs.readFileSync(path.join(TARGET_PATH,"app/build.gradle"), 'utf8');
            res = res.replace("implementation project(':libcocos2dx')",analytics[0].dependencies);
            saveFunc("app/build.gradle",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"build.gradle"), 'utf8');
            res = res.replace(/repositories {/g,analytics[0].buildscript);
            saveFunc("build.gradle",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/AndroidManifest.xml"), 'utf8');
            let permission="";
            for(let j=0;j<analytics[0].permission.length;j++){             
                if(j==0||res.indexOf(analytics[0].permission[j])==-1){
                    permission+=analytics[0].permission[j];
                }
            }            
            res = res.replace(analytics[0].permission[0],permission);                      
            saveFunc("app/AndroidManifest.xml",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/src/org/cocos2dx/javascript/AppActivity.java"), 'utf8');
            res = res.replace("package org.cocos2dx.javascript;",analytics[0].import);
            res = res.replace("super.onCreate(savedInstanceState);",analytics[0].onCreate);
            res = res.replace("super.onResume();",analytics[0].onResume);
            res = res.replace("super.onPause();",analytics[0].onPause);
            saveFunc("app/src/org/cocos2dx/javascript/AppActivity.java",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/src/org/cocos2dx/javascript/WDNativePlatform.java"), 'utf8');
            res = res.replace("package org.cocos2dx.javascript;",analytics[0].wdimport);
            res = res.replace("//==========>customEvent",analytics[0].customEvent);
            saveFunc("app/src/org/cocos2dx/javascript/WDNativePlatform.java",res);
        }  
        if(analytics[1].enable==true){
            if(config.android.vivoad.enable==true||config.android.oppoad.enable==true||config.android.marsad.enable==true) return;
            res = fs.readFileSync(path.join(TARGET_PATH,"app/build.gradle"), 'utf8');
            res = res.replace("implementation project(':libcocos2dx')",analytics[1].dependencies);
            res = res.replace("versionName \"1.0\"",analytics[1].buildscript1);
            res = res.replace("buildToolsVersion PROP_BUILD_TOOLS_VERSION",analytics[1].buildscript2);
            saveFunc("app/build.gradle",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/AndroidManifest.xml"), 'utf8');
            let permission="";
            for(let j=0;j<analytics[1].permission.length;j++){             
                if(j==0||res.indexOf(analytics[1].permission[j])==-1){
                    permission+=analytics[1].permission[j];
                }
            }            
            res = res.replace(analytics[1].permission[0],permission);                      
            saveFunc("app/AndroidManifest.xml",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/src/org/cocos2dx/javascript/AppActivity.java"), 'utf8');
            res = res.replace("super.onCreate(savedInstanceState);",analytics[1].onCreate);
            res = res.replace("super.onDestroy();",analytics[1].onDestroy);
            res = res.replace("package org.cocos2dx.javascript;",analytics[1].import);
            res = res.replace("super.onRequestPermissionsResult(requestCode, permissions, grantResults);",analytics[1].onRequestPermissionsResult);
            saveFunc("app/src/org/cocos2dx/javascript/AppActivity.java",res);
            res = fs.readFileSync(path.join(TARGET_PATH,"app/src/org/cocos2dx/javascript/WDNativePlatform.java"), 'utf8');
            res = res.replace("package org.cocos2dx.javascript;",analytics[1].wdimport);
            res = res.replace("//==========>customEvent",analytics[1].customEvent);
            res = res.replace("public static void register(){",analytics[1].register);
            res = res.replace("public static void loginSuccess(String jsStr){",analytics[1].loginSuccess);
            saveFunc("app/src/org/cocos2dx/javascript/WDNativePlatform.java",res);

            //复制文件
            checkDirectory("./admodule/reyun/libs",path.join(TARGET_PATH,"app/libs"),copy);
            fs.copyFile("././admodule/reyun/reyunWrapper.java",path.join(TARGET_PATH,"app/src/org/cocos2dx/javascript/reyunWrapper.java"),(err)=>{
                if(err) throw err;
            }) 
            fs.copyFile("././admodule/reyun/supplierconfig.json",path.join(TARGET_PATH,"app/assets/supplierconfig.json"),(err)=>{
                if(err) throw err;
            }) 
        }  
}
function saveFunc(url,data) {
    fs.writeFileSync(path.join(TARGET_PATH, url), data, 'utf8');
}


function copy(origin,target) {
    
    fs.readdir(origin, function(err,paths){
        if(err) throw err
        paths.forEach(function (url,index,arr) {
            let _origin=path.join(origin,url);
            let _target=path.join(target,url);
            fs.stat(_origin,function(err,stats){
                if(err) throw err;
                if(stats.isFile()){
                  let readable=fs.createReadStream(_origin);
                  let writable=fs.createWriteStream(_target); 
                  writable.on('close', function () {
                    console.log('复制完成')
                  }); 
                  readable.pipe(writable);
                }else if(stats.isDirectory()){
                    checkDirectory(_origin,_target,copy);
                }
            })
        });

    })
}
function checkDirectory(origin,target,callback) {
    try{
        fs.accessSync(target,fs.constants.F_OK);
        callback(origin,target);
    }catch(err){
        fs.mkdirSync(target);
        callback(origin,target);
    }
    
}
